package asg.pp;

import java.util.ArrayList;

import controller.Controller;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private ArrayList<User> userList;
	private ArrayList<Image> filterList;
	
	private ImageAdapter imageAdapter;
	private RelativeLayout mainLayout;
	private EditText edt;
	private GridView gridView;
	
	private PurblePlaceService service;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
		gridView = (GridView) findViewById(R.id.gridView);
		filterList = new ArrayList<Image>();
		imageAdapter = new ImageAdapter(this, filterList);
		gridView.setAdapter(imageAdapter);
		
		for(int i = 1; i <= 36; i++) {
			Image filterImage = new Image();
			filterList.add(filterImage);
			imageAdapter.notifyDataSetChanged();
		}
		
		edt = (EditText) findViewById(R.id.chatbox);
		edt.setVisibility(EditText.GONE);
		
		userList = new ArrayList<User>();
		service = PurblePlaceService.getInstance();
		service.setCurrentState(Controller.WAITSTART);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch(id) {
		case R.id.start_item:
			service.startGame();
			return true;
		case R.id.quit_item:
			service.quitGame(this);
			return true;
		case R.id.chat_item:
			// TODO
			((LinearLayout) findViewById(R.id.purble)).setVisibility(
					LinearLayout.GONE);
			
			
			edt.setVisibility(EditText.VISIBLE);
			
			edt.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					// TODO Auto-generated method stub
					if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER 
							|| keyCode == KeyEvent.KEYCODE_ENTER) {
						if(event.getAction() == KeyEvent.ACTION_DOWN) {	
							
							String text = edt.getText().toString().trim();
							if(!text.equals("")) {
								service.sendMessage(text);
								edt.setText("");
								edt.setVisibility(EditText.GONE);
								((LinearLayout) findViewById(
										R.id.purble)).setVisibility(LinearLayout.VISIBLE); 
							}
						}
					}
					return false;
				}
			});
			return true;
		}
		return false;
	}
}
